import axios from 'axios'
import { Toast } from 'vant'
import { triggerTipDialog } from '@/composition/errorTipDialogConfig'

// 创建实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // timeout: 5000 // 请求超时
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (!config.hideLoading) {
      Toast.loading({
        forbidClick: true,
      });
    }
    return config
  },
  error => {
    // 请求错误，可在此进行统一错误处理
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    const config = response.config
    if (!config.hideLoading) {
      Toast.clear()
    }
    if (res.msg === '系统繁忙') {
      triggerTipDialog({message: '系统异常错误，请联系在线客服查询！', title: '提示', show: true})
      throw new Error('系统繁忙')
    }
    if (res.code !== 200 && !config.noErrorTip) {
      Toast.fail({
        message: res.msg || 'Error',
        duration: 5 * 1000
      })

      return res
    } else {
      return res
    }
  },
  error => {
    Toast.clear()
    console.log('err' + error) // for debug
    Toast.fail({
      message: error.message,
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
